package wnhz.com.business.shareshop.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.groupshop.adapter.AllCommentAdapter;
import wnhz.com.business.groupshop.bean.AllCommentBean;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.shareshop.bean.ShopCommodityBean;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * 共享商城全部评论列表
 */
public class AllCommentActivityS extends BaseActivity implements ActionBarClickListener, View.OnClickListener {

    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.swipe_refresh_layout)
    XRefreshView xRefreshView;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.empty_layout)
    LinearLayout emptyLayout;
    private int paging = 0;//当前界面

    private AllCommentAdapter mAdapter;


    private String goodsId;

    private List<AllCommentBean.InfoBean.UserTalkBean> userTalkBean = new ArrayList<>();
    private List<ShopCommodityBean.InfoBean.CommontListBean> data = new ArrayList<>();
    private List<String> url = new ArrayList<>();

    public static Intent createIntent(Context context, String goodsId, String type) {
        Intent intent = new Intent(context, AllCommentActivityS.class);
        intent.putExtra("goodsId", goodsId);
        intent.putExtra("type", type);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_comments);
        ButterKnife.bind(this);
        goodsId = getIntent().getStringExtra("goodsId");
        actionbar.setData("全部评论", R.drawable.ic_lefft_white, null, 0, null, 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        setRefrash();
        initData();
        getData();
    }

    private void initData() {
        url.add("http://img4.imgtn.bdimg.com/it/u=882039601,2636712663&fm=21&gp=0.jpg");
        url.add("http://img4.imgtn.bdimg.com/it/u=4119861953,350096499&fm=21&gp=0.jpg");
        url.add("http://img5.imgtn.bdimg.com/it/u=2437456944,1135705439&fm=21&gp=0.jpg");
        AllCommentBean.InfoBean.UserTalkBean userTalkBean1 = new AllCommentBean.InfoBean.UserTalkBean();
        userTalkBean1.setUrl(url);
        userTalkBean1.setImg("http://img5.imgtn.bdimg.com/it/u=2024625579,507531332&fm=21&gp=0.jpg");
        userTalkBean.add(userTalkBean1);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }


    private void setRefrash() {
        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(AllCommentActivityS.this, LinearLayoutManager.VERTICAL, false));
        setData();//设置适配器
        //设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setAutoLoadMore(false);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.enablePullUpWhenLoadCompleted(true);
        xRefreshView.setOnRecyclerViewScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LogUtils.e("onScrollStateChanged");
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LogUtils.e("onScrolled");
            }
        });

        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        xRefreshView.stopRefresh();
                        paging = 0;
                        getData();//获取数据
                    }
                }, 500);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        paging++;
                        getData();//获取数据
                    }
                }, 1000);
            }
        });
    }

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("page", paging);
        map.put("goodsId", goodsId);
        XUtil.Post(Url.GOODS_EVALUATEDETAILLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.getString("re");
                    if ("1".equals(re)) {
                        Gson gson = new Gson();
                        ShopCommodityBean item = gson.fromJson(result, ShopCommodityBean.class);
                        if (paging == 0) {
                            data.clear();
                            data.addAll(item.getInfo().getCommont_list());
                            mAdapter.notifyDataSetChanged();
                        } else {
                            if (null != data) {
                                data.addAll(item.getInfo().getCommont_list());
                                mAdapter.notifyDataSetChanged();
                            } else {
                                //重置页数
                                paging = paging - 1;
                                xRefreshView.setLoadComplete(true);
                            }
//                            if(paging >= Integer.parseInt(item.getAll_paging()))
//                            {
//                                xRefreshView.setLoadComplete(true);
//                                //最后一页提示
////                                SnackbarUi.showInfoMsg(CommonUtils.getRootView(AllOrderActivity.this), resources.getString(R.string.last_page));
//                            }
                        }


                    } else {
                        if (paging == 0) {
                            data.clear();
                            mAdapter.notifyDataSetChanged();
                            ToastUtils.showToast(AllCommentActivityS.this, jsonObject.getString("info"));
                            emptyLayout.setVisibility(View.GONE);
                        } else {//加载更多时无数据
                            paging--;
                            emptyLayout.setVisibility(View.VISIBLE);
                            tvMsg.setText("暂无评价");
                        }
                        if ("-1".equals(jsonObject.getString("result"))) {
//                            toLogin(MessageActivity.this,MessageActivity.this,resources.getString(R.string.token_invalid),rightBarText);
                        } else if (!TextUtils.isEmpty(jsonObject.getString("info"))) {
                            ToastUtils.showToast(AllCommentActivityS.this, jsonObject.getString("info"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                xRefreshView.stopLoadMore();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    public void setData() {
        mAdapter = new AllCommentAdapter(AllCommentActivityS.this, data);
        recycler.setAdapter(mAdapter);
        mAdapter.setOnClickListener(new AllCommentAdapter.MyItemClickLinstener() {
            @Override
            public void OnPingJiaClickListener(AllCommentAdapter adapter, int position, View view) {
                Intent intent = new Intent(AllCommentActivityS.this, AllCommentActivitySS.class);
                intent.putExtra("commentId", data.get(position).getComment_id());
                intent.putExtra("is_like", data.get(position).getIs_like());
                startActivity(intent);
            }
        });
    }
}
